<?php
/**
 * Created by PhpStorm.
 * User: LiuJiaJun
 * Date: 2018/11/18
 * Time: 21:39
 */

namespace app\storage\controller;


use app\storage\model\CarModel;
use app\storage\model\CarSeatModel;
use app\storage\service\CarService;
use cmf\controller\AdminBaseController;
use think\Request;

class CarController extends AdminBaseController
{

    private $carModel;
    private $carSeatModel;
    use \app\storage\util\Common;
    public function __construct(CarModel $carModel, CarSeatModel $carSeatModel, Request $request = null)
    {
        parent::__construct($request);
        $this->carModel = $carModel;
        $this->carSeatModel = $carSeatModel;
    }

    public function index()
    {
        return $this->fetch('index');
    }

    public function add()
    {
        return $this->fetch('add');
    }

    public function getCar()
    {
        $where = $this->getWhere();
        unset ($where['where']);
        $result = $this->carModel->getCar($where);
        return json($result);
    }

    public function addCar()
    {
        $carService = new CarService();
        $carService->addCar();
        $this->redirect('storage/Car/index');
    }

    public function deleteCar()
    {
        $uuid = input('uuid');
        $result = $this->carModel->deleteCar($uuid);
        $msg = $result == true ?'删除成功':'删除失败';
        ajax_response($result, $msg);
    }

    public function getCarDetail()
    {
        $carUuid = input('carUuid');
        $result = $this->carSeatModel->getCarDetail($carUuid);
        return json($result);
    }


    public function getCarMaxId()
    {
        $carCode = $this->carModel->order('car_id asc')->distinct(true)->column("substr(car_id,3)");
        if (empty($carCode)) {
            $newCarId = 'HC0001';
        } else {
            $carCount = count($carCode);
            $maxCode = intval(end($carCode));
            $broken = $carCount == $maxCode ? $maxCode : 0;
            if (!$broken) {
                for ($i = 0; $i < $maxCode; $i++) {
                    if ($i + 1 != intval($carCode[$i])) {
                        $broken = $i;
                        break;
                    }
                }
            }
            if ($broken >= 9999) {
                return ajax_response(false, '超过系统预设最大值');
            }
            $newCarId = 'HC'.str_pad($broken+1,4,'0',STR_PAD_LEFT);
        }

        $carConfig = config('car');
        $data = [
            'newCarId' => $newCarId,
            'formatter' => $carConfig
        ];
        return ajax_response(true, '获取成功', $data);
    }


    public function checkCarId(){
        $carId = input('carId');
        $flag = $this->carModel->where('car_id',$carId)->find();
        return boolval(count($flag));
    }
}